package cn.texous.easytalk.websocket.strategy.message.chat;

import cn.texous.easytalk.commonutil.constant.Result;
import cn.texous.easytalk.commonutil.util.GsonUtils;
import cn.texous.easytalk.websocket.common.constants.ChatEnum;
import cn.texous.easytalk.websocket.common.util.MessageUtils;
import cn.texous.easytalk.websocket.foreign.EasytalkManagerFeignClient;
import cn.texous.easytalk.websocket.model.entity.ChatMsg;
import cn.texous.easytalk.websocket.model.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.lock.SetWithLock;
import org.tio.websocket.common.WsResponse;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/8/28 14:28
 */
@Component(EtChatMessageHandler.BEAN_NAME)
public class EtChatMessageHandler extends AbstractEtMessageHandler {

    /** bean name */
    public static final String BEAN_NAME = "etChatMessageHandler";

    @Autowired
    private EasytalkManagerFeignClient easytalkManagerFeignClient;

    @Override
    public Object handler(String msgText, ChannelContext channelContext) throws Exception {
        Result result = easytalkManagerFeignClient.test();
        System.out.println("------------------" + GsonUtils.toJson(result));
        Message<ChatMsg> message = MessageUtils.textToMessage(msgText, ChatMsg.class);
        ChatMsg chatMsg = message.getDetail();
        chatMsg.setMine(false);
        WsResponse wsResponse = WsResponse.fromText(msgText, serverConfig.getTioMsgCharset());
        //单聊
        if (ChatEnum.ChatType.SINGLE.equals(chatMsg.getType())) {
            SetWithLock<ChannelContext> channelContextSetWithLock = Tio
                    .getChannelContextsByUserid(channelContext.groupContext, chatMsg.getToId());
            //用户没有登录，存储到离线文件
            if (channelContextSetWithLock == null || channelContextSetWithLock.size() == 0) {
                saveMessage(chatMsg, ChatEnum.MsgStatus.UNREAD.getStatus());
            } else {
                Tio.sendToUser(channelContext.groupContext, chatMsg.getToId(), wsResponse);
                //入库操作
                saveMessage(chatMsg, ChatEnum.MsgStatus.HAVE_READ.getStatus());
            }
        } else {
            Tio.sendToGroup(channelContext.groupContext, chatMsg.getToId(), wsResponse);
            //入库操作
            saveMessage(chatMsg, ChatEnum.MsgStatus.HAVE_READ.getStatus());
        }
        return null;
    }

}
